#!/usr/bin/python
# Generator a port, and return , return it
# if not run ,open with vim , and ":set ff=unix"
import csv
import os
import subprocess
import random
import datetime
import copy


class GenPort(object):
    def __init__(self):
        self.data = self.get_db()
        self.ports = self.port_list()
        self.check_ports()
        self.random_port(self.ports)

    def port_list(self):
        ret = subprocess.Popen("netstat -tulnp", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        ret = ret.stdout.readlines()[2:]
        ports = list(set([i.split()[3].split(":")[-1] for i in ret]))
        return ports

    def get_db(self):
        if not os.path.exists("/var/log/tport.csv"):
            os.mknod("/var/log/tport.csv")
        with open("/var/log/tport.csv", "r") as f:
            reader = csv.reader(f)
            return list(reader)

    def random_port(self, exist_ports):
        port = random.randint(10000, 20000)
        if port in exist_ports or port in [int(i[0]) for i in self.data]:
            self.random_port(exist_ports)
        else:
            self.add_port_in_data(port)
            print port

    def check_ports(self):
        b = copy.deepcopy(self.data)
        for i in b:
            if i[0] not in self.ports:
                last_time = datetime.datetime.strptime(i[1], '%Y-%m-%d %H:%M:%S')
                now_time = datetime.datetime.now()
                seconds = (now_time - last_time).seconds
                if seconds > 600:
                    del self.data[self.data.index(i)]

    def add_port_in_data(self, port):
        self.data.append([port, datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')])
        with open("/var/log/tport.csv", "w") as f:
            writer = csv.writer(f)
            writer.writerows(self.data)


if __name__ == '__main__':
    a = GenPort()
